from PySide2 import QtWidgets
from PySide2.QtCore import Slot
from PySide2.QtWidgets import QLineEdit, QComboBox
from dayu_widgets import MLineEdit, MComboBox, MTableView, MTableModel, MClickBrowserFilePushButton
from dayu_widgets.field_mixin import MFieldMixin
from dayu_widgets.label import MLabel
from dayu_widgets.push_button import MPushButton
from dayu_widgets import dayu_theme
from NodeGraphQt import BaseNode
import pandas as pd


def getClassName():
    return "CsvInputNode"


class CsvInputNode(BaseNode):
    # unique node identifier.
    __identifier__ = '输入'

    # initial default node name.
    NODE_NAME = 'CSV Input'

    __node_window__ = None

    def __init__(self):
        super(CsvInputNode, self).__init__()

        # create node outputs.
        self.add_output('out')

        self.create_property("step_name", "")
        self.create_property("file_name", "")
        self.create_property("split", ",")
        self.create_property("encode", "utf-8")
        self.create_property("table", [])

    def show(self, isReload):
        if self.__node_window__ is None or isReload:
            self.__node_window__ = CsvInputNodeDialog(self)
            dayu_theme.apply(self.__node_window__)

        if self.__node_window__.isHidden():
            node = self.__node_window__
            node.step_name_line.setText(self.get_property("step_name"))
            node.file_name_line.setText(self.get_property("file_name"))
            node.split_name_line.setText(self.get_property("split"))
            node.encode_name_combo.set_value(self.get_property("encode"))
            node.table_model.set_data_list(self.get_property("table"))
            node.show()


class CsvInputNodeDialog(QtWidgets.QWidget, MFieldMixin):
    def __init__(self, csvInputNode: CsvInputNode, parent=None):
        super(CsvInputNodeDialog, self).__init__(parent)
        self.setWindowTitle(csvInputNode.name())
        self.resize(600, 400)

        main_lay = QtWidgets.QVBoxLayout()
        # step name
        step_name_lay = QtWidgets.QHBoxLayout()
        main_lay.addLayout(step_name_lay)
        step_name_lbl = MLabel("步骤名称")
        self.step_name_line = MLineEdit().small()
        step_name_lay.addWidget(step_name_lbl)
        step_name_lay.addWidget(self.step_name_line)

        # file name
        file_name_lay = QtWidgets.QHBoxLayout()
        main_lay.addLayout(file_name_lay)
        file_name_lbl = MLabel("文件名称")
        self.file_name_line = MLineEdit().small()
        file_name_browser_btn = MClickBrowserFilePushButton("浏览").small().primary()
        file_name_browser_btn.set_dayu_filters([".csv", ".txt", ".*"])
        self.register_field("current_file", "")
        self.bind("current_file", file_name_browser_btn, "dayu_path", signal="sig_file_changed")
        self.bind("current_file", self.file_name_line, "text")
        file_name_lay.addWidget(file_name_lbl)
        file_name_lay.addWidget(self.file_name_line)
        file_name_lay.addWidget(file_name_browser_btn)

        # split
        split_name_lay = QtWidgets.QHBoxLayout()
        main_lay.addLayout(split_name_lay)
        split_name_lbl = MLabel("列分隔符")
        self.split_name_line = MLineEdit().small()
        split_name_lay.addWidget(split_name_lbl)
        split_name_lay.addWidget(self.split_name_line)

        # encode
        encode_name_lay = QtWidgets.QHBoxLayout()
        main_lay.addLayout(encode_name_lay)
        encode_name_lbl = MLabel("文件编码")
        self.encode_name_combo = MComboBox().small()
        self.encode_name_combo.addItems(["utf-8", "gb2312"])
        self.encode_name_combo.setProperty("searchable", True)
        encode_name_lay.addWidget(encode_name_lbl)
        encode_name_lay.addWidget(self.encode_name_combo)

        # table
        self.table_model = MTableModel()
        self.table_model.set_header_list(table_header_list())
        self.table_model.set_data_list(table_default_data_list())
        table_grid = MTableView(size=dayu_theme.small, show_row_count=True)
        table_grid.setShowGrid(True)
        table_grid.setModel(self.table_model)
        main_lay.addWidget(table_grid)

        # button
        grid_lay = QtWidgets.QGridLayout()
        center_name_lay = QtWidgets.QHBoxLayout()
        main_lay.addLayout(grid_lay)

        help_btn = MLabel().warning()
        help_btn.set_link("https://gitee.com/default-null/python_study_demo", text="帮助")

        ok_btn = MPushButton("确定").small().success()
        ok_btn.clicked.connect(lambda: self.onOk(csvInputNode))

        get_field_btn = MPushButton("获取字段").small()
        get_field_btn.clicked.connect(lambda: self.onGetFields(csvInputNode))

        preview_btn = MPushButton("预览").small()
        preview_btn.clicked.connect(lambda: self.onPreview(csvInputNode))

        cancel_btn = MPushButton("取消").small().danger()
        cancel_btn.clicked.connect(lambda: self.onCancel(csvInputNode))

        grid_lay.addWidget(help_btn, 1, 0)
        grid_lay.addLayout(center_name_lay, 1, 1)

        center_name_lay.addStretch(1)  # 前面增加一行
        center_name_lay.addWidget(ok_btn)
        center_name_lay.addWidget(get_field_btn)
        center_name_lay.addWidget(preview_btn)
        center_name_lay.addWidget(cancel_btn)
        center_name_lay.addStretch(1)  # 前面增加一行

        self.setLayout(main_lay)

    def onOk(self, node: CsvInputNode):
        node.set_property("step_name", self.step_name_line.text())
        node.set_property("file_name", self.file_name_line.text())
        node.set_property("split", self.split_name_line.text())
        node.set_property("encode", self.encode_name_combo.currentText())
        table_data_list = self.table_model.get_data_list()
        for row in table_data_list:
            del row["_parent"]
        node.set_property("table", table_data_list)
        self.close()

    def onCancel(self, node: CsvInputNode):
        print(node.model.to_dict)
        self.close()

    def onHelp(self, node: CsvInputNode):
        pass

    def onGetFields(self, node: CsvInputNode):
        df = pd.read_csv(self.file_name_line.text())
        columns = df.columns
        print(columns)
        column_list = list(df.columns.values)
        data_list = []
        for column in column_list:
            header = {"name": column, "type": "", "format": ""}
            data_list.append(header)
        self.table_model.set_data_list(data_list)

    def onPreview(self, node: CsvInputNode):
        pass


def table_default_data_list():
    data_list = [
        {
            "name": "",
            "type": "",
            "format": ""
        },
        {
            "name": "",
            "type": "",
            "format": ""
        },
        {
            "name": "",
            "type": "",
            "format": ""
        },
        {
            "name": "",
            "type": "",
            "format": ""
        },
        {
            "name": "",
            "type": "",
            "format": ""
        }
    ]
    return data_list


def table_header_list():
    header_list = [
        {
            "label": "名称",
            "key": "name",
            "width": 200
        },
        {
            "label": "类型",
            "key": "type",
            "width": 200
        },
        {
            "label": "格式",
            "key": "format",
            "width": 200
        }
    ]

    return header_list


if __name__ == '__main__':
    # Import local modules
    from dayu_widgets import dayu_theme
    from dayu_widgets.qt import application

    with application() as app:
        csvNode = CsvInputNode()
        test = CsvInputNodeDialog(csvNode)
        dayu_theme.apply(test)
        test.show()
